package com.gs.order.service.impl;


import com.gs.common.constant.UserConstants;
import com.gs.common.utils.StringUtils;
import com.gs.common.utils.snowflake.SnowflakeIdWorker;
import com.gs.gaosheng.domain.GsOrder;
import com.gs.gaosheng.domain.User;
import com.gs.order.mapper.OrderMapper;
import com.gs.order.service.IOrderService;
import com.gs.order.vo.OrderInfoVo;
import com.gs.order.vo.OrderVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private OrderMapper orderMapper;


    /**
     * 生成订单号存入缓存
     * @return
     */
    @Override
    public String makeOrderId() {
        Long num = SnowflakeIdWorker.generateId();
        String orderNum = num + "";
        stringRedisTemplate.opsForValue().set(orderNum, orderNum, 1, TimeUnit.MINUTES);
        return orderNum;
    }

    /**
     * 判断和缓存订单号判断，防止篡改
     * @param orderNum
     * @return
     */
    @Override
    public boolean isOrderIdOk(String orderNum) {
        if(!Objects.isNull(orderNum)){
            String oid =stringRedisTemplate.opsForValue().get(orderNum);
            if(StringUtils.isNotEmpty(oid)) {
                return true;
            }
            return false;
        }
        return false;
    }

    /**
     * 存入订单表
     * @param orderVo
     */
    @Override
    public void makeOrder(OrderVo orderVo) {
        //1. 获取到订单id
        String orderNum = orderVo.getOrderNum();
//        Long oNum = Long.valueOf(orderNum);

        //3. 创建订单对象
        GsOrder gsOrder = new GsOrder();
        gsOrder.setOrderNum(orderNum);
        gsOrder.setGoodsName(orderVo.getGoodsName());
        gsOrder.setGoodsCount(orderVo.getGoodsCount());
        gsOrder.setOrderStatus(1L);
        gsOrder.setOrderTotal(orderVo.getOrderTotal());
        gsOrder.setOrderTotalPay(orderVo.getOrderTotalPay());
        gsOrder.setOrderTime(new Date());
        gsOrder.setShowFlag(1L);
        gsOrder.setOrderPlat(orderVo.getOrderPlat());
        gsOrder.setOrderScore(orderVo.getOrderScore());
        gsOrder.setOrderCoupon(orderVo.getOrderCoupon());
        gsOrder.setOrderCouponId(orderVo.getOrderCouponId());
        gsOrder.setUserId(orderVo.getUserId());
        gsOrder.setGoodsId(orderVo.getGoodsId());

        //4. 插入订单信息
        orderMapper.insert(gsOrder);

        //6. 将信息生产到延时队列中
        rabbitTemplate.convertAndSend(UserConstants.DELAY_ORDER_EXCHANGE, UserConstants.DELAY_ORDER_ROUTING_KEY, orderNum);
    }

    /**
     * 修改订单状态
     * @param state
     * @param orderNum
     * @return
     */
    @Override
    public Integer updateOrder(Long state, String orderNum) {

        List<GsOrder> orders = orderMapper.selectList(orderNum);
        orders.forEach(order -> {
            order.setOrderStatus(state);
            orderMapper.update(order);
        });
        return null;
    }

    /**
     * 查看我的订单
     * @param userId
     * @return
     */
    @Override
    public List<OrderInfoVo> findorder(Long userId) {
        List<OrderInfoVo> gsOrders = orderMapper.findOrders(userId);
        return gsOrders;
    }

    /**
     * 添加用户积分
     * @param orderNum
     */
    @Override
    public void addscore(String orderNum){
        GsOrder order = orderMapper.getInfo(orderNum);
        User user = orderMapper.getUserInfo(order.getUserId());
        Long allscore = 0L;
        if (user.getUserScore()==null){
            allscore = order.getOrderScore();
        }else {
             allscore = user.getUserScore()+order.getOrderScore();
        }
        System.out.println(allscore);
        user.setUserScore(allscore);
        orderMapper.updateUser(user);


    }


    /**
     * 根据订单号查询秒杀商品信息并存入秒杀表
     * @param num
     * @return
     */
  @Override
  public Long selectGoodsByNamePlat(String num) {
    GsOrder gsOrders = orderMapper.selectOrder(num);
    Long userId = gsOrders.getUserId();
    Long goodsId = gsOrders.getGoodsId();
    orderMapper.insertSecKillOrder(userId,goodsId);
    return null;
  }

    @Override
    public Long changeCouponStatus(String out_trade_no) {
        GsOrder gsOrders = orderMapper.getInfo(out_trade_no);
         Long id = gsOrders.getOrderCouponId();
        System.out.println(id);
         orderMapper.updateCoupon(id);
return null;
    }


    /**
     * 延时队列监听
     * @param orderNum
     */
  @RabbitListener(queues = {UserConstants.DLX_ORDER_QUEUE})
    public void cancelOrder(String orderNum) {
        //1. 查询订单信息
        GsOrder order = orderMapper.getInfo(orderNum);
        //2. 修改订单状态
        if (order.getOrderStatus() == 1) {
            order.setOrderStatus(3L);
            orderMapper.update(order);
        }
    }

}
